<?php

class PortalData
{
    private static $_dataArray;
    private static $lastModifiedTime = 0;

	/**
	 * 获取DB Object
	 * @param $type int
	 * @return RecordObject
	 **/
	public static function getDbConn($type=0,$destination='db')
	{
		static $conn=array();
		static $target = array("reader","writer");
		static $class = array("ReadableRecordFactory","WritableRecordFactory");

		$config = ConfigReaderFactory::getInstance()->getConfigReader(AC::PORTAL_CONFIG_FILE)->getConfig();
		$db     = $config->$destination;
		$conn_name = $type.$destination;

		if(!isset($conn[$conn_name])){
			$conn[$conn_name] = new $class[$type] ($db->$target[$type],$db->user,(string)$db->pwd,$db->name);
		}
		return $conn[$conn_name];
	}

    public static function selectBySql($sql,array $param=array()){
        $dbo_r = self::getDbConn(0,'pdes_db3');
        $dbo_w = self::getDbConn(1,'pdes_db3');

		$dbo =  $dbo_r->getDbHandle();
        $dbo->query("SET time_zone = '+8:00'");
		try
		{
			$smt      = $dbo->prepare($sql);
			$exec_ret = $smt->execute($param);
		}
		catch(Exception $e)
		{
			error_log("ERROR CLASS:" . __CLASS__ . ", FUNCTION: " . __FUNCTION__ . ", LINE: " . __LINE__);
			error_log("ERROR - SQL FAILS: $sql");
			error_log("Parameters: " . print_r($param, TRUE));
			error_log(print_r($smt->errorInfo(), TRUE));
			error_log("Exception Message: ".$e->getMessage());
			//throw $e;
			return array();
		}
		return $smt->fetchAll(PDO::FETCH_ASSOC);
	}


    /**
     * get programme details from pms.pdes by programme id 
     * @param $programme_id : programme id
     * @return array
     */
    public static function getPortalData($table_name ,$id ,$record_status='') 
    {
        self::$_dataArray = array();

        if('p_programme' == strtolower($table_name))
        {
            $data_array = array(
                'p_programme'                 =>  array(),
                'p_folder'                    =>  array(),
                'p_folder_image'              =>  array(),
                'p_folder_video'              =>  array(),
                'p_image'                     =>  array(),
                'p_video'                     =>  array(),
                'p_cast'                      =>  array(),
                'p_chapter'                   =>  array()

            );
            $folder_list = self::getFolderById('p_programme', $id);
            $img_video = self::getImgOrVideo('p_programme',$id);
            self::mergeDataArray(self::$_dataArray, $img_video);

            $data_array['p_programme']= self::getPmsProgramme($id);
            
            $data_array['p_cast'] = isset($data_array['p_programme'][0]) ? self::getPmsCasts('p_programme',$id, $data_array['p_programme'][0]) : array() ;
            $folder_list_cast = self::getFolderByCast($data_array['p_cast']); 
            self::mergeFolderList($folder_list, $folder_list_cast);

            $data_array['p_chapter'] = self::getPmsChapterByProgrammeId($id);
            
            $data_array['p_folder'] = isset($folder_list['folder']) ? $folder_list['folder'] : array();
            $data_array['p_folder_image'] = isset($folder_list['image']) ? $folder_list['image'] : array() ;
            $data_array['p_folder_video'] = isset($folder_list['video']) ? $folder_list['video'] : array();

            $data_array['p_image'] =  isset(self::$_dataArray['image']) ? self::$_dataArray['image'] : array() ;
            $data_array['p_video'] =  isset(self::$_dataArray['video']) ? self::$_dataArray['video'] : array();
        }
        else
        if('p_episode' == strtolower($table_name))
        {
            $data_array = array(
                'p_episode'                   =>  array(),
                'p_folder'                    =>  array(),
                'p_folder_image'              =>  array(),
                'p_image'                     =>  array(),
                'p_info'                      =>  array(),
                'p_cast'                      =>  array()

            );
            $folder_list = self::getFolderById('p_episode', $id);
            $img_video = self::getImgOrVideo('p_episode',$id);
            self::mergeDataArray(self::$_dataArray, $img_video);

            $data_array['p_episode'] = self::getPmsEpisodeById($id); 

            $data_array['p_cast'] = self::getPmsCasts('p_episode',$id, $data_array['p_episode'][0]);
            $folder_list_cast = !isset($data_array['p_episode'][0]['onair_episode_no']) ? array() : self::getFolderByCast($data_array['p_cast'], $id, $data_array['p_episode'][0]['onair_episode_no']); 
            self::mergeFolderList($folder_list, $folder_list_cast);

            $data_array['p_folder'] = isset($folder_list['folder']) ? $folder_list['folder'] : array();
            $data_array['p_folder_image'] = isset($folder_list['image']) ? $folder_list['image'] : array() ;

            $data_array['p_image'] =  isset(self::$_dataArray['image']) ? self::$_dataArray['image'] : array() ;
            $data_array['p_info'] = self::getPmsInfosByEpisodeId($id, $data_array['p_episode'][0]);

			// bug 7287
			// by donald at 2011-10-10
			$p_video_list = p_video::getAll(
				array(
					'episode_id' => $id,
					'onair_episode_no' => 0
				)
			);
			foreach ($p_video_list as $p_video) {
				$data_array['p_video'][] = NewPortalData::getPortalVideo($p_video->id);

				$p_folder_video_list = p_folder_video::getAll(
					array(
						'video_id' => $p_video->id
					)
				);
				foreach ($p_folder_video_list as $p_folder_video) {
					$p_folder_item = NewPortalData::getServiceFolderItem($p_folder_video->folder_id, $p_folder_video->video_id);
					$data_array['p_folder_video'][] = NewPortalData::getPortalFolderVideo($p_folder_item);
				}

				$p_chapter_list = p_chapter::getAll(
					array(
						'video_id' => $p_video->id
					)
				);
				foreach ($p_chapter_list as $p_chapter) {
					$data_array['p_chapter'][] = NewPortalData::getPortalChapter($p_chapter->id);
				}
			}
        }
        else
        {
           $data_array = array(); 
        }
        //return array('type'=>$record_status,'data'=>$programme_details);
        return $data_array;
    
    }
    
    public static function getFolderByCast(array $casts, $episode_id='', $onair_no='')
    {
        $folder_list = array();
        foreach ($casts as $cast) { 
            $folder_list_new = self::getFolderById('p_personage', $cast['id'], $cast['programme_id'], $episode_id, $onair_no);
            self::mergeFolderList($folder_list, $folder_list_new);

            $image_video = self::getImgOrVideo('p_personage', $cast['id'], $cast['programme_id'], $episode_id, $onair_no);
            self::mergeDataArray(self::$_dataArray, $image_video);
        }
    
        return $folder_list;
    }

    private static function mergeFolderList(&$folder_list_old, $folder_list_new)
    {
        foreach ($folder_list_new as $type=>$data) {
            if (is_array($data) && !empty($data)) {
                foreach ($data as $row) {
                    $folder_list_old[$type][] = $row;
                }
            }
        }
    }

    private static function mergeDataArray(&$dataArray, $_new_data)
    {
        foreach ($_new_data as $type=>$data) {
            if (is_array($data) && !empty($data)) {
                foreach ($data as $row) {
                    $dataArray[$type][] = $row;
                }
            }
        }
    }

    public static function getLastModifyTime($datetime)
	{
        if(self::$lastModifiedTime <= $datetime )
        {
            self::$lastModifiedTime = $datetime; 
        }
        return date('Y-m-d H:i:s',self::$lastModifiedTime);
    }

    private static function getIdsByEpisodeId($table_name,$id)
    {
        $result = array();
        $sql = 'SELECT  id FROM `'.$table_name.'` WHERE episode_id = :id'; 
        $ret = self::selectBySql($sql,array(':id'=>$id));
        if(!empty($ret))
        {
            foreach($ret as $val)
            {
                $result[] = $val['id'];
            }
        }
        return empty($result) ? '' : implode(',',$result);
    }

    private static function getInfoExtra($type,$info_type,$data)
    {
        $infoTypes = array(
            1=>'address',
            'award',
            'biography',
            'general_information',
            'product',
            'q_a',
            'recipe',
            'song',
        );
        $infos = (array)json_decode($data);
        $result = '';
        switch($infoTypes[$info_type])
        {
        case 'address' :
            if('title' == $type)
            {
                $result = empty($infos['venue_name_chinese']) ? $infos['venue_name_english'] : $infos['venue_name_chinese']; 
            }
            if('description' == $type)
            {
                $result = isset($infos['description']) ? $infos['description'] : ''; 
            }
            ;break;
        case 'award' :  
            if('title' == $type)
            {
                $result = empty($infos['award_title_chinese']) ? $infos['award_title_english'] : $infos['award_title_chinese']; 
            }
            if('description' == $type)
            {
                $result = isset($infos['description']) ? $infos['description'] : ''; 
            }
            ;break;
        case 'biography' :  
            if('title' == $type)
            {
                $result = empty($infos['name_chinese']) ? $infos['name_english'] : $infos['name_chinese']; 
            }
            if('description' == $type)
            {
                $result = isset($infos['description']) ? $infos['description'] : ''; 
            }
            ;break;
        case 'general_information' :
            if('title' == $type)
            {
                $result = empty($infos['title_chinese']) ? $infos['title_english'] : $infos['title_chinese']; 
            }
            if('description' == $type)
            {
                $result = isset($infos['description']) ? $infos['description'] : ''; 
            }
            ;break;

        case 'product' :
            if('title' == $type)
            {
                $result = empty($infos['product_name_chinese']) ? $infos['product_name_english'] : $infos['product_name_chinese']; 
            }
            if('description' == $type)
            {
                $result = isset($infos['description']) ? $infos['description'] : ''; 
            }
            ;break;

        case 'q_a' :
            if('title' == $type)
            {
                $result = empty($infos['question']) ? '' : $infos['question']; 
            }
            if('description' == $type)
            {
                $result = isset($infos['answer']) ? $infos['answer'] : ''; 
            }
            ;break;

        case 'recipe' : 
            if('title' == $type)
            {
                $result = empty($infos['dish_name_chinese']) ? $infos['dish_name_english'] : $infos['dish_name_chinese']; 
            }
            if('description' == $type)
            {
                $result = isset($infos['description']) ? $infos['description'] : ''; 
            }
            ;break;
        case 'song' :
            if('title' == $type)
            {
                $result = empty($infos['title_chinese']) ? $infos['title_english'] : $infos['title_chinese']; 
            }
            if('description' == $type)
            {
                $result = isset($infos['description']) ? $infos['description'] : ''; 
            }
            ;break;
        }
        return $result;
    }

    public static function getPmsInfosByEpisodeId($episode_id, $episode_detail)
    {
        $info_array = array();
		$sql = '
			SELECT * ,
                UNIX_TIMESTAMP(modified_at) as modified_at,
                UNIX_TIMESTAMP(created_at) as created_at,
                UNIX_TIMESTAMP(online_time) as online_time,
                UNIX_TIMESTAMP(offline_time) as offline_time
            FROM `p_info` WHERE episode_id = :id
            '; 
        $ret = self::selectBySql($sql,array(':id'=>$episode_id));
        if (empty($ret)) {
            return $info_array;
        }

        foreach($ret as $row) {
            $info = NULL;
            $info->info_id = $row['info_id'];
			$info->info_type_id = $row['info_type_id'];
			$info->programme_id = $episode_detail['programme_id'];
			$info->episode_id = $row['episode_id'];
			$info->onair_episode_no = $episode_detail['onair_episode_no'];
			$info->video_id = self::getIdsByEpisodeId('p_video',$episode_id);
			$info->chapter_id = self::getIdsByEpisodeId('p_chapter',$episode_id);
			$info->online_time = $row['online_time'];
			$info->offline_time = $row['offline_time'];
			$info->created_at = $row['created_at'];
			$info->modified_at = $row['modified_at'];
			$info->title = self::getInfoExtra('title',$row['info_type_id'],$row['extras']);
			$info->description = self::getInfoExtra('description',$row['info_type_id'],$row['extras']);
            $info->extras = $row['extras'];
			$info->video_type = $episode_detail['video_type'];
			$info->premium_title = $episode_detail['premium_title'];
			$info->premium_title_zh = $episode_detail['premium_title_zh'];
			$info->premium_title_en = $episode_detail['premium_title_en'];
			$info->ppv_flag = $episode_detail['ppv_flag'];
			$info->ppv_online_time = $episode_detail['ppv_online_time'];
			$info->ppv_offline_time = $episode_detail['ppv_offline_time'];
			$info->ppv_country_allow_list = $episode_detail['ppv_country_allow_list'];
			$info->ppv_country_deny_list = $episode_detail['ppv_country_deny_list'];
			$info->subscription_flag = $episode_detail['subscription_flag'];
			$info->subscription_free_flag = $episode_detail['subscription_free_flag'];
			$info->subscription_online_time = $episode_detail['subscription_online_time'];
			$info->subscription_offline_time = $episode_detail['subscription_offline_time'];
			$info->subscription_country_allow_list = $episode_detail['subscription_country_allow_list'];
			$info->subscription_country_deny_list = $episode_detail['subscription_country_deny_list'];

            self::getLastModifyTime($row['modified_at']);
            $info_array[] = (array) $info;
        }

        return $info_array;
    }

    private static function getPmsEpisodeById($id)
    {
        $episode_array = array();
        $sql = 'SELECT *, 
            UNIX_TIMESTAMP(time_onair) as time_onair,UNIX_TIMESTAMP(modified_at) as modified_at,
            UNIX_TIMESTAMP(created_at) as created_at,UNIX_TIMESTAMP(online_time) as online_time,
            UNIX_TIMESTAMP(offline_time) as offline_time
            FROM `p_episode` WHERE id = :id'; 
        $ret = self::selectBySql($sql,array(':id'=>$id));
        if(!empty($ret))
        {
            foreach($ret as $epi)
            {
                $sql = 'SELECT id FROM `p_folder_item-video` WHERE episode_id = :eid and folder_type = "regular" limit 1';
                $ret = self::selectBySql($sql,array(':eid'=>$id));
                if($ret)
                {
                    $premium_data = self::getFieldById('p_video',$ret[0]['id']);
                    if(empty($premium_data))
                    {
                        $premium_data = self::getFieldById('p_programme',$pid);
                    }
                }
                else
                {
                    $premium_data = self::getFieldById('p_programme',$epi['programme_id']);
                }
                //$episode['uri'] = 'subscription_episode_'.$epi['id'];
                $episode['id'] = $epi['id'];
                $episode['programme_id'] = $epi['programme_id'];
                $episode['onair_episode_no'] = $epi['episode_number'];
                $episode['first_time_onair'] = $epi['time_onair'];
                $episode['other_language_episodes'] =  $epi['other_language_episodes'];
                $episode['online_time'] = isset($epi['online_time']) ? $epi['online_time'] : '';
                $episode['offline_time'] = isset($epi['offline_time']) ? $epi['offline_time'] : '';
                //$episode['country_allow_list'] = isset($epi['country_allow_list']) ? $epi['country_allow_list'] : '';
                //$episode['country_deny_list'] = isset($epi['country_deny_list']) ? $epi['country_deny_list'] : '';
                $episode['created_at'] = $epi['created_at'];
                $episode['modified_at'] = $epi['modified_at'];
                $episode['casts'] = $epi['casts'];
                $episode['title'] = $epi['title'];
                $episode['title_zh'] = $epi['title_chinese'];
                $episode['title_en'] = $epi['title_english'];
                $episode['description'] = $epi['description'];
                $episode['description_zh'] = $epi['description_chinese'];
                $episode['description_en'] = $epi['description_english'];
                $episode['description_short'] = $epi['description_short'];
                $episode['description_short_zh'] = $epi['description_short_chinese'];
                $episode['description_short_en'] = $epi['description_short_english'];
                $episode['editor_message'] = $epi['editor_message'];
                $episode['editor_message_zh'] = $epi['editor_message_chinese'];
                $episode['editor_message_en'] = $epi['editor_message_english'];
                $episode['rates'] = $epi['rating'];

                $episode['video_type'] = isset($premium_data['video_type']) ? $premium_data['video_type'] : 'O';
                $episode['ppv_flag'] = isset($premium_data['ppv_flag']) ? $premium_data['ppv_flag'] : 0;
                $episode['subscription_flag'] = isset($premium_data['subscription_flag']) ? $premium_data['subscription_flag'] : 0;
                $episode['premium_title'] = isset($premium_data['premium_title']) ? $premium_data['premium_title'] : '';
                $episode['premium_title_zh'] = isset($premium_data['premium_title_zh']) ? $premium_data['premium_title_zh'] : '';
                $episode['premium_title_en'] = isset($premium_data['premium_title_en']) ? $premium_data['premium_title_en'] : '';
                $episode['ppv_online_time'] = isset($premium_data['ppv_online_time']) ? $premium_data['ppv_online_time'] : '';
                $episode['ppv_offline_time'] = isset($premium_data['ppv_offline_time']) ? $premium_data['ppv_offline_time'] : '';
                $episode['ppv_country_allow_list'] = isset($premium_data['ppv_country_allow_list']) ? $premium_data['ppv_country_allow_list'] : '';
                $episode['ppv_country_deny_list'] = isset($premium_data['ppv_country_deny_list']) ? $premium_data['ppv_country_deny_list'] : '';
                $episode['subscription_free_flag'] = isset($premium_data['subscription_free_flag']) ? $premium_data['subscription_free_flag'] : 0;
                $episode['subscription_online_time'] = isset($premium_data['subscription_online_time']) ? $premium_data['subscription_online_time'] : '';
                $episode['subscription_offline_time'] = isset($premium_data['subscription_offline_time']) ? $premium_data['subscription_offline_time'] : '';
                $episode['subscription_country_allow_list'] = isset($premium_data['subscription_country_allow_list']) ? $premium_data['subscription_country_allow_list'] : '';
                $episode['subscription_country_deny_list'] = isset($premium_data['subscription_country_deny_list']) ? $premium_data['subscription_country_deny_list'] : '';

                self::getLastModifyTime($epi['modified_at']);
                //$episode_cast = self::getCastsById('episode',$id);
                $episode_array[] = $episode;
           
            }
        }
        return $episode_array;
    
    }

    public static function getPmsChapterByProgrammeId($programme_id)
    {
        $chapter_array = array();
        $sql = '
            SELECT * ,
                UNIX_TIMESTAMP(created_at) as created_at,
                UNIX_TIMESTAMP(modified_at) as modified_at,
                UNIX_TIMESTAMP(online_time) as online_time,
                UNIX_TIMESTAMP(offline_time) as offline_time
            FROM `p_chapter` WHERE programme_id = :pid
            ';
        $ret = self::selectBySql($sql,array(':pid'=>$programme_id));
        if (empty($ret)) {
            return $chapter_array; 
        }

        $programme_detail = self::getFieldById('p_programme',$programme_id);

        foreach ($ret as $row) {
            $episode_detail = self::getFieldById('p_episode',$row['episode_id']);
            $video_detail = self::getPmsVideoById($row['video_id']);

            $chapter->id = $row['id'];
			$chapter->programme_id = $row['programme_id'];
			$chapter->episode_id = $row['episode_id'];
			$chapter->onair_episode_no = isset($episode_detail['episode_number']) ? $episode_detail['episode_number'] : '';
			$chapter->video_id = $row['video_id'];
			$chapter->in_time = $row['in_time'];
			$chapter->out_time = $row['out_time'];
            $chapter->primary_category_id = isset($programme_detail['primary_category_id']) ? $programme_detail['primary_category_id'] :'';
			$chapter->created_at = $row['created_at'];
			$chapter->modified_at = $row['modified_at'];
			$chapter->tags = $row['tags'];
			$chapter->ii_data = $row['image_id'];
			$chapter->title = $row['title'];
			$chapter->title_zh = $row['title_chinese'];
			$chapter->title_en = $row['title_english'];
			$chapter->description = $row['description'];
			$chapter->description_zh = $row['description_chinese'];
			$chapter->description_en = $row['description_english'];
			$chapter->casts = $row['casts'];
			$chapter->categories = $row['categories'];
			$chapter->infos = $row['infos'];
			$chapter->video_type = $video_detail['video_type'];
			$chapter->premium_title = $video_detail['premium_title'];
			$chapter->premium_title_zh = $video_detail['premium_title_zh'];
			$chapter->premium_title_en = $video_detail['premium_title_en'];
			$chapter->ppv_flag = $video_detail['ppv_flag'];
			$chapter->ppv_online_time = $video_detail['ppv_online_time'];
			$chapter->ppv_offline_time = $video_detail['ppv_offline_time'];
			$chapter->ppv_country_allow_list = $video_detail['ppv_country_allow_list'];
			$chapter->ppv_country_deny_list = $video_detail['ppv_country_deny_list'];
			$chapter->subscription_flag = $video_detail['subscription_flag'];
			$chapter->subscription_free_flag = $video_detail['subscription_free_flag'];
			$chapter->subscription_online_time = $video_detail['subscription_online_time'];
			$chapter->subscription_offline_time = $video_detail['subscription_offline_time'];
			$chapter->subscription_country_allow_list = $video_detail['subscription_country_allow_list'];
			$chapter->subscription_country_deny_list = $video_detail['subscription_country_deny_list'];

            $chapter_array[] = (array) $chapter;
            self::getLastModifyTime($row['modified_at']);
        }

        return $chapter_array;
    }

    public static function getPmsVideoById($video_id)
    {
        $sql = '
            SELECT * ,
                UNIX_TIMESTAMP(modified_at) as modified_at,
                UNIX_TIMESTAMP(created_at) as created_at,
                UNIX_TIMESTAMP(online_time) as online_time,
                UNIX_TIMESTAMP(offline_time) as offline_time,
                UNIX_TIMESTAMP(ppv_online_time) as ppv_online_time,
                UNIX_TIMESTAMP(ppv_offline_time) as ppv_offline_time,
                UNIX_TIMESTAMP(subscription_online_time) as subscription_online_time,
                UNIX_TIMESTAMP(subscription_offline_time) as subscription_offline_time 
            FROM `p_video` WHERE id = :id
            '; 
        $ret = self::selectBySql($sql, array(':id' => $video_id));
        return empty($ret) ? array() : array_shift($ret);
    }

    private static function getImgOrVideo($table_name, $id, $programme_id='', $episode_id='', $onair_no='')
    {
        $list = array();
        $sql = 'SELECT `folders` FROM `'.$table_name.'` WHERE id = :id';
        $ret = self::selectBySql($sql,array(':id'=>$id));
        if( isset($ret[0]['folders'])  )
        {
            $folders = json_decode($ret[0]['folders']);
            if(!empty($folders))
            {
                $_data = self::getFieldById($table_name,$id);

                //$publish_time = isset($_data['premium_publish_datetime_field']) ? $_data['premium_publish_datetime_field'] : '';
                //$expire_time = isset($_data['premium_expire_datetime_field']) ? $_data['premium_expire_datetime_field'] : '';
                //$allow_country = isset($_data['premium_country_allow_list']) ? $_data['premium_country_allow_list'] : '';
                //$deny_country = isset($_data['premium_country_deny_list']) ? $_data['premium_country_deny_list'] : '';
                $first_time =  isset($_data['first_episode_time_onair']) ? $_data['first_episode_time_onair'] : '';
                if('p_programme' == $table_name)
                {
                    $pid = $id;
                    $eid = '';
                    $onair_no = '';
                }
                if('p_episode' == $table_name)
                {
                    $pid = isset($_data['programme_id']) ? $_data['programme_id'] : '';
                    $eid = $id;
                    $onair_no = isset($_data['episode_number']) ? $_data['episode_number'] : '';
                }

                if ('p_personage' == $table_name) {
                    $pid = $programme_id;
                    $eid = $episode_id;
                    $onair_no = $onair_no;
                }

                foreach($folders as $folder_val)
                {
                    #$folder_items = $folder_val->items;
                    #if(isset($folder_items[0]))
					if(isset($folder_val->items) && is_array($folder_val->items))
					foreach($folder_val->items as $f_item)
                    {
                        #$f_item = $folder_items[0];
                        if('image' === self::checkItemType($f_item->item_type) )
                        {
                            $item_val = self::getFieldById('p_image', $f_item->item_id);
                            if(!empty($item_val))
                            {
                                $programme_ret = self::getFieldById('p_programme', $item_val['programme_id']);
                                $item = array();
                                //$item['uri'] = 'subscription_image_'.$item_val['id'];
                                $item['id'] = $item_val['id'];
                                $item['programme_id'] = $item_val['programme_id'];
                                $item['episode_id'] = $eid;
                                $item['onair_episode_no'] = $onair_no;
                                //$item['folder_list'] = self::getFolderList($table_name,'image',$id);
                                $item['folder_list'] = self::getFolderListByImageId($item_val['id']);
                                $item['online_time'] =  isset($item_val['online_time']) ? $item_val['online_time'] : '' ;
                                $item['offline_time'] = isset($item_val['offline_time']) ? $item_val['offline_time'] : '' ;
                                $item['country_allow_list'] = isset($item_val['country_allow_list']) ? $item_val['country_allow_list'] : '' ;
                                $item['country_deny_list'] = isset($item_val['country_deny_list']) ? $item_val['country_deny_list'] : '' ;
                                $item['created_at'] = $item_val['created_at'];
                                $item['modified_at'] = $item_val['modified_at'];
                                $item['tags'] = $item_val['tags'];
                                $item['ii_data'] = $item_val['ii_id'];
                                $item['title'] = $item_val['title'];
                                $item['title_zh'] = $item_val['title_chinese'];
                                $item['title_en'] = $item_val['title_english'];
                                
                                $item['video_type'] = isset($programme_ret['video_type']) ? $programme_ret['video_type'] : 'O';
                                $item['ppv_flag'] = isset($programme_ret['ppv_flag']) ? $programme_ret['ppv_flag'] : 0;
                                $item['subscription_flag'] = isset($programme_ret['subscription_flag']) ? $programme_ret['subscription_flag'] : 0;
                                $item['premium_title'] = isset($programme_ret['premium_title']) ? $programme_ret['premium_title'] : '';
                                $item['premium_title_zh'] = isset($programme_ret['premium_title_zh']) ? $programme_ret['premium_title_zh'] : '';
                                $item['premium_title_en'] = isset($programme_ret['premium_title_en']) ? $programme_ret['premium_title_en'] : '';
                                $item['ppv_online_time'] = isset($programme_ret['ppv_online_time']) ? $programme_ret['ppv_online_time'] : '';
                                $item['ppv_offline_time'] = isset($programme_ret['ppv_offline_time']) ? $programme_ret['ppv_offline_time'] : '';
                                $item['ppv_country_allow_list'] = isset($programme_ret['ppv_country_allow_list']) ? $programme_ret['ppv_country_allow_list'] : '';
                                $item['ppv_country_deny_list'] = isset($programme_ret['ppv_country_deny_list']) ? $programme_ret['ppv_country_deny_list'] : '';
                                $item['subscription_free_flag'] = isset($programme_ret['subscription_free_flag']) ? $programme_ret['subscription_free_flag'] : 0;
                                $item['subscription_online_time'] = isset($programme_ret['subscription_online_time']) ? $programme_ret['subscription_online_time'] : '';
                                $item['subscription_offline_time'] = isset($programme_ret['subscription_offline_time']) ? $programme_ret['subscription_offline_time'] : '';
                                $item['subscription_country_allow_list'] = isset($programme_ret['subscription_country_allow_list']) ? $programme_ret['subscription_country_allow_list'] : '';
                                $item['subscription_country_deny_list'] = isset($programme_ret['subscription_country_deny_list']) ? $programme_ret['subscription_country_deny_list'] : '';

                                $list['image'][] = $item;
                                self::getLastModifyTime($item_val['modified_at']);
                            }
                        }

                        if('video' === self::checkItemType($f_item->item_type) )
                        {
                            $item_val = self::getFieldById('p_video', $f_item->item_id);
                            if(!empty($item_val))
                            {
                                $item = array();
                                //$item['uri'] = 'subscription_video_'.$item_val['id'];
                                $item['id'] = $item_val['id'];
                                $item['programme_id'] = $item_val['programme_id'];
                                //$item['episode_id'] = $eid;
                                $item['episode_id'] = self::getEpisodeIdByVideoId($f_item->item_id);
                                #$item['onair_episode_no'] = $onair_no;
                                $item['onair_episode_no'] = self::getEpisodeNumberByVideoId($f_item->item_id);//$onair_no;
                                //$item['folder_list'] = self::getFolderList($table_name,'video',$id);
                                $item['folder_list'] = self::getFolderListByVideoId($item_val['id']);
                                $item['folder_type_path'] = self::getFolderListPathByFolderId($item['folder_list']);
                                //$item['is_free'] = isset($item_val['is_free']) ? $item_val['is_free'] : 1;
                                $item['online_time'] =  isset($item_val['online_time']) ? $item_val['online_time'] : '' ;
                                $item['offline_time'] = isset($item_val['offline_time']) ? $item_val['offline_time'] : '' ;
                                $item['country_allow_list'] = isset($item_val['country_allow_list']) ? $item_val['country_allow_list'] : '' ;
                                $item['country_deny_list'] = isset($item_val['country_deny_list']) ? $item_val['country_deny_list'] : '' ;
                                $item['created_at'] = $item_val['created_at'];
                                $item['modified_at'] = $item_val['modified_at'];
                                $item['first_time_onair'] = $item_val['first_time_onair'];//$first_time;
                                //$item['seo_list'] = $item_val['tags'];
                                $item['ii_data'] = $item_val['image_id'];
                                $item['vi_data'] = $item_val['vi_id'];
                                $item['title'] = $item_val['title'];
                                $item['title_zh'] = $item_val['title_chinese'];
                                $item['title_en'] = $item_val['title_english'];
                                $item['subtitle'] = $item_val['subtitle'];
                                $item['breakpoint'] = $item_val['breakpoint'];
                                $item['duration'] =  $item_val['duration'];
                                $item['tags'] =  $item_val['tags'];
                                $item['other_videos'] = $item_val['other_videoes'];
                                $item['source_id'] = isset( $item_val['source_id']) ? $item_val['source_id'] : '';     
                                
                                $item['video_type'] = isset($item_val['video_type']) ? $item_val['video_type'] : 'O';
                                $item['ppv_flag'] = isset($item_val['ppv_flag']) ? $item_val['ppv_flag'] : 0;
                                $item['subscription_flag'] = isset($item_val['subscription_flag']) ? $item_val['subscription_flag'] : 0;
                                $item['premium_title'] = isset($item_val['premium_title']) ? $item_val['premium_title'] : '';
                                $item['premium_title_zh'] = isset($item_val['premium_title_zh']) ? $item_val['premium_title_zh'] : '';
                                $item['premium_title_en'] = isset($item_val['premium_title_en']) ? $item_val['premium_title_en'] : '';
                                $item['ppv_online_time'] = isset($item_val['ppv_online_time']) ? $item_val['ppv_online_time'] : '';
                                $item['ppv_offline_time'] = isset($item_val['ppv_offline_time']) ? $item_val['ppv_offline_time'] : '';
                                $item['ppv_country_allow_list'] = isset($item_val['ppv_country_allow_list']) ? $item_val['ppv_country_allow_list'] : '';
                                $item['ppv_country_deny_list'] = isset($item_val['ppv_country_deny_list']) ? $item_val['ppv_country_deny_list'] : '';
                                $item['subscription_free_flag'] = isset($item_val['subscription_free_flag']) ? $item_val['subscription_free_flag'] : 0;
                                $item['subscription_online_time'] = isset($item_val['subscription_online_time']) ? $item_val['subscription_online_time'] : '';
                                $item['subscription_offline_time'] = isset($item_val['subscription_offline_time']) ? $item_val['subscription_offline_time'] : '';
                                $item['subscription_country_allow_list'] = isset($item_val['subscription_country_allow_list']) ? $item_val['subscription_country_allow_list'] : '';
                                $item['subscription_country_deny_list'] = isset($item_val['subscription_country_deny_list']) ? $item_val['subscription_country_deny_list'] : '';

                                $obj = new MstatWebServiceClient();
                                $ret = $obj->getVideoStats(1,AC::PERIOD);
                                if( is_array($ret) && !empty($ret) )
                                {
                                    $_data = array();
                                    foreach($ret as $_id => $data)
                                    {
                                        if(intval($_id) == intval($item_val['id']))
                                        {
                                            $item['mytv_plus_view'] = $data['view'];
                                            $item['total_view'] = $data['view'];
                                            $item['mytv_plus_fav'] = $data['favour'];
                                            $item['total_fav'] = $data['favour'];
                                        }
                                    }
                                }

                                $list['video'][] = $item;     

                                self::getLastModifyTime($item_val['modified_at']);
                            }
                        }
                    }
                }
            }
        }
        return $list;
    }

    public static function getFolderListByImageId($image_id)
    {
        $sql = 'SELECT GROUP_CONCAT(`folder_id`) AS folder_list FROM `p_folder_item-image` WHERE id = :id';
        $ret = self::selectBySql($sql, array(':id'=>$image_id));
        return $ret[0]['folder_list'] ? $ret[0]['folder_list'] : '';
    }

    public static function getFolderListByVideoId($video_id)
    {
        $sql = 'SELECT GROUP_CONCAT(`folder_id`) AS folder_list FROM `p_folder_item-video` WHERE id = :id';
        $ret = self::selectBySql($sql, array(':id'=>$video_id));
        return $ret[0]['folder_list'] ? $ret[0]['folder_list'] : '';
    }

//    private static function getFolderList($table ,$type, $id)
//    {
//        $result = array();
//        if('episode' == $table && 'image' == $type)
//        {
//            $sql = 'SELECT folder_id FROM `folder_item-'.$type.'` WHERE programme_id = :id';
//        }
//        else
//        {
//            $sql = 'SELECT folder_id FROM `folder_item-'.$type.'` WHERE '.$table.'_id = :id';
//        }
//        $ret = self::selectBySql($sql,array(':id'=>$id));
//        if(!empty($ret))
//        {
//            foreach($ret as $val)
//            {
//                $result[] = $val['folder_id'];
//            }
//        }
//        return empty($result) ? '' : implode(',',$result);
//    }

	private static function getEpisodeIdByVideoId($id){
        $sql = 'select ifnull(v.episode_id,0) id from `p_video` v left join `p_episode` e on v.episode_id = e.id where v.id = :id';
        $ret = self::selectBySql($sql,array(':id'=>$id));
        return isset($ret[0]['id']) ? $ret[0]['id'] : 0;
	}

	private static function getEpisodeNumberByVideoId($id){
        $sql = 'select ifnull(e.episode_number,"") number from `p_video` v left join `p_episode` e on v.episode_id = e.id where v.id = :id';
        $ret = self::selectBySql($sql,array(':id'=>$id));
        return isset($ret[0]['number']) ? $ret[0]['number'] : '';
	}

    private static function getFolderById($table_name, $id, $programme_id='', $episode_id='', $onair_no='')
    {
        $folder_list = array();
        $folder_arr = $folder_image = $folder_video = array();
        $sql = 'SELECT `folders`
                FROM `'.$table_name.'` WHERE id = :id';
        $ret = self::selectBySql($sql,array(':id'=>$id));
        if( isset($ret[0]['folders'])  )
        {
            $folders = json_decode($ret[0]['folders']);
            if(!empty($folders))
            {
                $_data = self::getFieldById($table_name,$id);

                //$publish_time = isset($_data['premium_publish_datetime_field']) ? $_data['premium_publish_datetime_field'] : '';
                //$expire_time = isset($_data['premium_expire_datetime_field']) ? $_data['premium_expire_datetime_field'] : '';
                //$allow_country = isset($_data['premium_country_allow_list']) ? $_data['premium_country_allow_list'] : '';
                //$deny_country = isset($_data['premium_country_deny_list']) ? $_data['premium_country_deny_list'] : '';
                $first_time =  isset($_data['first_episode_time_onair']) ? $_data['first_episode_time_onair'] : '';
                switch ($table_name) {
                case 'p_programme':
                    $pid = $id;
                    $eid = '';
                    $onair_no = '';
                    $_cast_id = '';
                    $premium_data = $_data;
                    break;
                case 'p_episode':
                    $pid = isset($_data['programme_id']) ? $_data['programme_id'] :'';
                    $eid = $id;
                    $onair_no = isset($_data['episode_number']) ?$_data['episode_number'] : '' ;
                    $_cast_id = '';
                    $sql = 'SELECT id FROM `p_folder_item-video` WHERE episode_id = :eid and folder_type = "regular" limit 1';
                    $ret = self::selectBySql($sql,array(':eid'=>$id));
                    if($ret)
                    {
                        $premium_data = self::getFieldById('p_video',$ret[0]['id']);
                        if(empty($premium_data))
                        {
                            $premium_data = self::getFieldById('p_programme',$pid);
                        }
                    }
                    else
                    {
                        $premium_data = self::getFieldById('p_programme',$pid);
                    }
                    break;
                case 'p_personage':
                    $pid = $programme_id; 
                    $eid = $episode_id;
                    $onair_no = $onair_no;
                    $_cast_id = $id;
                    break;
                }

                $video_type = isset($premium_data['video_type']) ? $premium_data['video_type'] : 'O';
                $ppv_flag = isset($premium_data['ppv_flag']) ? $premium_data['ppv_flag'] : 0;
                $subscription_flag = isset($premium_data['subscription_flag']) ? $premium_data['subscription_flag'] : 0;
                $premium_title = isset($premium_data['premium_title']) ? $premium_data['premium_title'] : '';
                $premium_title_zh = isset($premium_data['premium_title_zh']) ? $premium_data['premium_title_zh'] : '';
                $premium_title_en = isset($premium_data['premium_title_en']) ? $premium_data['premium_title_en'] : '';
                $ppv_online_time = isset($premium_data['ppv_online_time']) ? $premium_data['ppv_online_time'] : '';
                $ppv_offline_time = isset($premium_data['ppv_offline_time']) ? $premium_data['ppv_offline_time'] : '';
                $ppv_country_allow_list = isset($premium_data['ppv_country_allow_list']) ? $premium_data['ppv_country_allow_list'] : '';
                $ppv_country_deny_list = isset($premium_data['ppv_country_deny_list']) ? $premium_data['ppv_country_deny_list'] : '';
                $subscription_free_flag = isset($premium_data['subscription_free_flag']) ? $premium_data['subscription_free_flag'] : 0;
                $subscription_online_time = isset($premium_data['subscription_online_time']) ? $premium_data['subscription_online_time'] : '';
                $subscription_offline_time = isset($premium_data['subscription_offline_time']) ? $premium_data['subscription_offline_time'] : '';
                $subscription_country_allow_list = isset($premium_data['subscription_country_allow_list']) ? $premium_data['subscription_country_allow_list'] : '';
                $subscription_country_deny_list = isset($premium_data['subscription_country_deny_list']) ? $premium_data['subscription_country_deny_list'] : '';

                foreach($folders as $folder_val)
                {
                    $folder['id'] = $folder_val->id;
                    $folder['folder_type_path'] = $folder_val->type;
                    $folder['contains'] = $folder_val->contains;
                    $folder['programme_id'] = $pid;
                    $folder['episode_id'] = $eid;
                    $folder['onair_episode_no'] = $onair_no;
                    $folder['cast_id'] = $_cast_id;
                    $folder['created_at'] = isset($_data['created_at']) ? $_data['created_at'] : 0;
                    $folder['modified_at'] = isset($_data['modified_at']) ? $_data['modified_at'] : 0;
                    $folder['title'] = $folder_val->title;
                    $folder['title_zh'] = $folder_val->title_chinese;
                    $folder['title_en'] = $folder_val->title_english;
                    $folder['video_type'] = $video_type;
                    $folder['ppv_flag'] = $ppv_flag;
                    $folder['subscription_flag'] = $subscription_flag;
                    $folder['premium_title'] = $premium_title;
                    $folder['premium_title_zh'] = $premium_title_zh;
                    $folder['premium_title_en'] = $premium_title_en;
                    $folder['ppv_online_time'] = $ppv_online_time;
                    $folder['ppv_offline_time'] = $ppv_offline_time;
                    $folder['ppv_country_allow_list'] = $ppv_country_allow_list;
                    $folder['ppv_country_deny_list'] = $ppv_country_deny_list;
                    $folder['subscription_free_flag'] = $subscription_free_flag;
                    $folder['subscription_online_time'] = $subscription_online_time;
                    $folder['subscription_offline_time'] = $subscription_offline_time;
                    $folder['subscription_country_allow_list'] = $subscription_country_allow_list;
                    $folder['subscription_country_deny_list'] = $subscription_country_deny_list;

                    $folder_arr[] = $folder;

                    self::getLastModifyTime($folder['modified_at']);
                    #$folder_items = $folder_val->items;
                    #if(isset($folder_items[0]))
					if(isset($folder_val->items) && is_array($folder_val->items))
					foreach($folder_val->items as $f_item)
                    {
                        #$f_item = $folder_items[0];
                        if('image' === self::checkItemType($f_item->item_type) )
                        {
                            $item = array();
                            $image_data = self::getFieldById('p_image', $f_item->item_id);
                            if(!empty($image_data))
                            {
                                $programme_ret = self::getFieldById('p_programme', $pid);
                               // $item['uri'] = 'subscription_folder_image_'.$f_item->folder_id.'_'.$f_item->item_id;
                                $item['folder_id'] = $f_item->folder_id;
                                $item['folder_type_path'] = $f_item->folder_type ;
                                $item['image_id'] = $f_item->item_id;
                                $item['rank'] = $f_item->rank;
                                $item['programme_id'] = $pid;
                                $item['episode_id'] = $eid;
                                $item['onair_episode_no'] = $onair_no;
                                //$item['folder_list'] = self::getFolderList($table_name,'image',$id);
                                $item['folder_list'] = self::getFolderListByImageId($f_item->item_id);
                                $item['online_time'] = $image_data['online_time'];
                                $item['offline_time'] = $image_data['offline_time'];
                                $item['country_allow_list'] = isset($image_data['country_allow_list']) ? $image_data['country_allow_list'] : '';
                                $item['country_deny_list'] = isset($image_data['country_deny_list']) ? $image_data['country_deny_list'] : '';
                                $item['created_at'] = $image_data['created_at'];
                                $item['modified_at'] = $image_data['modified_at'];
                                $item['tags'] = $image_data['tags'];
                                $item['ii_data'] = $image_data['ii_id'];
                                $item['title'] = $f_item->title;
                                $item['title_zh'] =  $f_item->title_chinese;
                                $item['title_en'] =  $f_item->title_english;
                                
                                $item['video_type'] = isset($programme_ret['video_type']) ? $programme_ret['video_type'] : 'O';
                                $item['ppv_flag'] = isset($programme_ret['ppv_flag']) ? $programme_ret['ppv_flag'] : 0;
                                $item['subscription_flag'] = isset($programme_ret['subscription_flag']) ? $programme_ret['subscription_flag'] : 0;
                                $item['premium_title'] = isset($programme_ret['premium_title']) ? $programme_ret['premium_title'] : '';
                                $item['premium_title_zh'] = isset($programme_ret['premium_title_zh']) ? $programme_ret['premium_title_zh'] : '';
                                $item['premium_title_en'] = isset($programme_ret['premium_title_en']) ? $programme_ret['premium_title_en'] : '';
                                $item['ppv_online_time'] = isset($programme_ret['ppv_online_time']) ? $programme_ret['ppv_online_time'] : '';
                                $item['ppv_offline_time'] = isset($programme_ret['ppv_offline_time']) ? $programme_ret['ppv_offline_time'] : '';
                                $item['ppv_country_allow_list'] = isset($programme_ret['ppv_country_allow_list']) ? $programme_ret['ppv_country_allow_list'] : '';
                                $item['ppv_country_deny_list'] = isset($programme_ret['ppv_country_deny_list']) ? $programme_ret['ppv_country_deny_list'] : '';
                                $item['subscription_free_flag'] = isset($programme_ret['subscription_free_flag']) ? $programme_ret['subscription_free_flag'] : 0;
                                $item['subscription_online_time'] = isset($programme_ret['subscription_online_time']) ? $programme_ret['subscription_online_time'] : '';
                                $item['subscription_offline_time'] = isset($programme_ret['subscription_offline_time']) ? $programme_ret['subscription_offline_time'] : '';
                                $item['subscription_country_allow_list'] = isset($programme_ret['subscription_country_allow_list']) ? $programme_ret['subscription_country_allow_list'] : '';
                                $item['subscription_country_deny_list'] = isset($programme_ret['subscription_country_deny_list']) ? $programme_ret['subscription_country_deny_list'] : '';

                                $folder_image[] = $item;
                                self::getLastModifyTime($image_data['modified_at']);
                            }
                        }

                        if('video' === self::checkItemType($f_item->item_type) )
                        {
                            $item = array();
                            $video_data = self::getFieldById('p_video', $f_item->item_id);
                            if(!empty($video_data))
                            {
                                //$item['uri'] = 'subscription_folder_video_'.$f_item->folder_id.'_'.$f_item->item_id;
                                $item['folder_id'] = $f_item->folder_id;
                                $item['folder_type_path'] = $f_item->folder_type ;
                                $item['video_id'] = $f_item->item_id;
                                $item['rank'] = $f_item->rank;
                                $item['programme_id'] = $pid;
                                $item['episode_id'] = self::getEpisodeIdByVideoId($f_item->item_id);
                                $item['onair_episode_no'] = self::getEpisodeNumberByVideoId($f_item->item_id);//$onair_no;
                                //$item['is_free'] = isset($video_data['is_free']) ? $video_data['is_free'] : 0 ;
                                $item['online_time'] = isset($video_data['online_time']) ? $video_data['online_time'] : '';
                                $item['offline_time'] = isset($video_data['offline_time']) ? $video_data['offline_time'] : '';
                                $item['country_allow_list'] = isset($video_data['country_allow_list']) ? $video_data['country_allow_list'] : '';
                                $item['country_deny_list'] = isset($video_data['country_deny_list']) ? $video_data['country_deny_list'] : '';
                                $item['created_at'] = $video_data['created_at'];
                                $item['modified_at'] = $video_data['modified_at'];
                                $item['tags'] = $video_data['tags'];
                                $item['vi_data'] = $video_data['vi_id'];
                                $item['first_time_onair'] = $video_data['first_time_onair'];//$first_time;
                                $item['title'] = $f_item->title;
                                $item['title_zh'] =  $f_item->title_chinese;
                                $item['title_en'] =  $f_item->title_english;
                                $item['subtitle'] =  $video_data['subtitle'];
                                
                                $item['video_type'] = isset($video_data['video_type']) ? $video_data['video_type'] : 'O';
                                $item['ppv_flag'] = isset($video_data['ppv_flag']) ? $video_data['ppv_flag'] : 0;
                                $item['subscription_flag'] = isset($video_data['subscription_flag']) ? $video_data['subscription_flag'] : 0;
                                $item['premium_title'] = isset($video_data['premium_title']) ? $video_data['premium_title'] : '';
                                $item['premium_title_zh'] = isset($video_data['premium_title_zh']) ? $video_data['premium_title_zh'] : '';
                                $item['premium_title_en'] = isset($video_data['premium_title_en']) ? $video_data['premium_title_en'] : '';
                                $item['ppv_online_time'] = isset($video_data['ppv_online_time']) ? $video_data['ppv_online_time'] : '';
                                $item['ppv_offline_time'] = isset($video_data['ppv_offline_time']) ? $video_data['ppv_offline_time'] : '';
                                $item['ppv_country_allow_list'] = isset($video_data['ppv_country_allow_list']) ? $video_data['ppv_country_allow_list'] : '';
                                $item['ppv_country_deny_list'] = isset($video_data['ppv_country_deny_list']) ? $video_data['ppv_country_deny_list'] : '';
                                $item['subscription_free_flag'] = isset($video_data['subscription_free_flag']) ? $video_data['subscription_free_flag'] : 0;
                                $item['subscription_online_time'] = isset($video_data['subscription_online_time']) ? $video_data['subscription_online_time'] : '';
                                $item['subscription_offline_time'] = isset($video_data['subscription_offline_time']) ? $video_data['subscription_offline_time'] : '';
                                $item['subscription_country_allow_list'] = isset($video_data['subscription_country_allow_list']) ? $video_data['subscription_country_allow_list'] : '';
                                $item['subscription_country_deny_list'] = isset($video_data['subscription_country_deny_list']) ? $video_data['subscription_country_deny_list'] : '';

                                $folder_video[] = $item;
                                self::getLastModifyTime($video_data['modified_at']);
                            }
                        }
                    }

                }
                    $folder_list['folder'] = $folder_arr;
                    $folder_list['image'] = $folder_image;
                    $folder_list['video'] = $folder_video;
            }
        }
        return $folder_list;
    }

    private static function checkItemType($id)
    {
        $sql = 'SELECT name FROM `item_types` WHERE id = :id';
        $ret = self::selectBySql($sql,array(':id'=>$id));
        return isset($ret[0]['name']) ? $ret[0]['name'] : false;
    }

    public static function getPmsCastById($cast_id, $parent)
    {
        $sql = '
            SELECT *,
                UNIX_TIMESTAMP(created_at) as created_at,
                UNIX_TIMESTAMP(modified_at) as modified_at 
            FROM `p_personage` WHERE id = :id
            ';
        $result = self::selectBySql($sql, array(':id'=>$cast_id));
        if (empty($result)) {
            return array();
        } 

        $row = array_shift($result);

        $cast = NULL;
        $cast->id = $row['id'];
        $cast->programme_id = $row['programme_id'];
        $cast->cast_role_id = $row['cast_role_id'];
        $cast->created_at = $row['created_at'];
        $cast->modified_at = $row['modified_at'];
        $cast->gender = $row['gender'];
        $cast->age = $row['age'];
        $cast->blog_url = $row['blogUrl'];
        $cast->real_first_name = $row['real_first_name'];
        $cast->real_first_name_zh = $row['real_first_name_chinese'];
        $cast->real_first_name_en = $row['real_first_name_english'];
        $cast->real_last_name = $row['real_last_name'];
        $cast->real_last_name_zh = $row['real_last_name_chinese'];
        $cast->real_last_name_en = $row['real_last_name_english'];
        $cast->real_name = $row['real_name'];
        $cast->real_name_zh = $row['real_name_chinese'];
        $cast->real_name_en = $row['real_name_english'];
        $cast->other_name = $row['other_name'];
        $cast->other_name_zh = $row['other_name_chinese'];
        $cast->other_name_en = $row['other_name_english'];
        $cast->nickname = $row['nickname'];
        $cast->nickname_zh = $row['nickname_chinese'];
        $cast->nickname_en = $row['nickname_english'];
        $cast->occupation = $row['occupation'];
        $cast->occupation_zh = $row['occupation_chinese'];
        $cast->occupation_en = $row['occupation_english'];
        $cast->personality = $row['personality'];
        $cast->personality_zh = $row['personality_chinese'];
        $cast->personality_en = $row['personality_english'];
        $cast->profile = $row['profile'];
        $cast->profile_zh = $row['profile_chinese'];
        $cast->profile_en = $row['profile_english'];
        $cast->history = $row['history'];
        $cast->history_zh = $row['history_chinese'];
        $cast->history_en = $row['history_english'];
        $cast->video_type = $parent['video_type'];
        $cast->premium_title = $parent['premium_title'];
        $cast->premium_title_zh = $parent['premium_title_zh'];
        $cast->premium_title_en = $parent['premium_title_en'];
        $cast->ppv_flag = $parent['ppv_flag'];
        $cast->ppv_online_time = $parent['ppv_online_time'];
        $cast->ppv_offline_time = $parent['ppv_offline_time'];
        $cast->ppv_country_allow_list = $parent['ppv_country_allow_list'];
        $cast->ppv_country_deny_list = $parent['ppv_country_deny_list'];
        $cast->subscription_flag = $parent['subscription_flag'];
        $cast->subscription_free_flag = $parent['subscription_free_flag'];
        $cast->subscription_online_time = $parent['subscription_online_time'];
        $cast->subscription_offline_time = $parent['subscription_offline_time'];
        $cast->subscription_country_allow_list = $parent['subscription_country_allow_list'];
        $cast->subscription_country_deny_list = $parent['subscription_country_deny_list'];

        self::getLastModifyTime($row['modified_at']);
        return (array) $cast;
    }

    private static function getPmsCasts($table_name, $id, $parent)
    {
        $cast_array = array();
        $sql = 'SELECT raw_casts FROM `'.$table_name.'` WHERE id = :id';
        $ret = self::selectBySql($sql,array(':id'=>$id));
        if (empty($ret)) {
            return  $cast_array ;
        }

        $casts = json_decode($ret[0]['raw_casts']);
        if (empty($casts)) {
            return  $cast_array ;
        }

        foreach($casts as $cast_val) {
            if(is_array($cast_val)) {
                foreach($cast_val as $val) {
                    if (!empty($val->cast_id)) {
                        $_cast = self::getPmsCastById($val->cast_id, $parent);
                        if (!empty($_cast)) {
                            $cast_array[] = $_cast;
                        }
                    }
                }
            }
        }

        return  $cast_array ;
    }


    private static function getPmsCategory($id)
    {
        $cate_array = array();
        $sql = '
            SELECT * FROM `p_category_new` c
            left join `p_programme-category` pc on pc.category_id_1 = c.id
            where pc.programme_id = :pid
        '; 
        $ret = self::selectBySql($sql,array(':pid'=>$id));
        if(isset($ret[0]))
        {
            foreach($ret as $val)
            {
                $cate['uri'] = 'subscription_category_'.$val['id'];
                $cate['id'] = $val['id'];
                $cate['path'] = $val['path'];
                $cate['parent_id'] = $val['parent_id'];
                $cate['forum_id'] = $val['forum_id'];
                $cate['title'] = $val['name'];
                $cate['title_zh'] = $val['name_chinese'];
                $cate['title_en'] = $val['name_english'];
                $cate_array[] = $cate;
            }
        }
        return $cate_array;
    }

//  public static function getPmsCategoryById($category_id)
//  {
//      return self::getFieldById('category_new', $category_id);
//  }
    
    private static function getPmsProgrammeChannel($id)
    {
        $channel_array = array();
        $sql = '
            SELECT * FROM `p_channel` c
            left join `p_programme-channel` pc on pc.network_code = c.code
            where pc.programme_id = :pid
        '; 
        $ret = self::selectBySql($sql,array(':pid'=>$id));
        if(isset($ret[0]))
        {
            foreach($ret as $val)
            {
                $channel['uri'] = 'subscription_channel_'.$val['code'];
                $channel['code'] = $val['code'];
                $channel['path'] = $val['path'];
                $channel['channel_no'] = $val['channel_no'];
                $channel['title'] = $val['title_chinese'];
                $channel['title_zh'] = $val['title_chinese'];
                $channel['title_en'] = $val['title_english'];
                $channel_array[] = $channel;
            }
        }
        return $channel_array;

    }

    public static function getPmsProgramme($id)
    {
        $programme_array = array();
        $sql = 'SELECT * ,
            UNIX_TIMESTAMP(time_onair) as time_onair, UNIX_TIMESTAMP(first_episode_time_onair) as first_episode_time_onair,  
            UNIX_TIMESTAMP(last_episode_time_onair) as last_episode_time_onair, UNIX_TIMESTAMP(created_at) as created_at , 
            UNIX_TIMESTAMP(modified_at) as modified_at, UNIX_TIMESTAMP(production_start_date) as production_start_date,
            UNIX_TIMESTAMP(online_time) as online_time, UNIX_TIMESTAMP(offline_time) as offline_time, 
            UNIX_TIMESTAMP(ppv_online_time) as ppv_online_time, UNIX_TIMESTAMP(ppv_offline_time) as ppv_offline_time, 
            UNIX_TIMESTAMP(subscription_online_time) as subscription_online_time, 
            UNIX_TIMESTAMP(subscription_offline_time) as subscription_offline_time 
            FROM `p_programme` WHERE id = :pid'; 
        $ret = self::selectBySql($sql,array(':pid'=>$id));
        if(isset($ret[0]))
        {
            $pro = $ret[0];
            //$programme['uri'] = 'subscription_programme_'.$pro['id'];
            $programme['id'] = $pro['id'];
            $programme['path'] =  $pro['path'];
            $programme['primary_category_id'] = $pro['primary_category_id'];
            $programme['category_list'] = self::getCategoryList($id);
            $programme['first_network_codes'] = $pro['first_network_code'];
            $programme['first_episode_time_onair'] = $pro['first_episode_time_onair'];
            $programme['last_episode_time_onair'] = $pro['last_episode_time_onair'];
            $programme['meta_keywords'] = $pro['meta_keywords'];
            $programme['meta_description'] = $pro['meta_description'];
            $programme['casts'] = $pro['casts'];
            $programme['online_time'] = isset($pro['online_time']) ? $pro['online_time'] : '';
            $programme['offline_time'] = isset($pro['offline_time']) ? $pro['offline_time'] : '';
            //$programme['country_allow_list'] = isset($pro['premium_country_allow_list']) ? $pro['premium_country_allow_list'] : '';
            //$programme['country_deny_list'] = isset($pro['premium_country_deny_list']) ? $pro['premium_country_deny_list'] : '';
            $programme['created_at'] = $pro['created_at'];
            $programme['modified_at'] = $pro['modified_at'];
            $programme['number_of_episodes'] = $pro['number_of_episodes'];
            $programme['minisite_url'] = $pro['minisite_url'];
            $programme['blog_url'] = $pro['blog_url'];
            $programme['forum_id'] = $pro['forum_id'];
            $programme['title'] = $pro['name_chinese'] ? $pro['name_chinese'] : $pro['name_english'];
            $programme['title_zh'] = $pro['name_chinese'];
            $programme['title_en'] = $pro['name_english'];
            $programme['description'] = $pro['description'];
            $programme['description_zh'] = $pro['description_chinese'];
            $programme['description_en'] = $pro['description_english'];
            $programme['description_short'] = $pro['description_short'];
            $programme['description_short_zh'] = $pro['description_short_chinese'];
            $programme['description_short_en'] = $pro['description_short_english'];
            $programme['first_onair_information'] = $pro['channelInfoPremiere'];
            $programme['first_onair_information_zh'] = $pro['channelInfoPremiere_chinese'];
            $programme['first_onair_information_en'] = $pro['channelInfoPremiere_english'];
            $programme['tags'] = $pro['tags'];
            $programme['nominal_duration'] = $pro['nominal_duration'];
            $programme['banner_image'] = $pro['banner_image'];
            $programme['key_art_image'] = $pro['key_art_image'];
            $programme['first_time_onair'] = $pro['time_onair'];
            $programme['objective'] = $pro['objective'];
            $programme['starting_episode_no'] = $pro['starting_episode_no'];
            $programme['production_start_date'] = $pro['production_start_date'];
            $programme['fact_background'] = isset($pro['fact_background']) ? $pro['fact_background'] :'';
            $programme['fact_background_zh'] = isset($pro['fact_background_chinese']) ? $pro['fact_background_chinese'] : '';
            $programme['fact_background_en'] = isset($pro['fact_background_english']) ? $pro['fact_background_english'] : '';
            $programme['video_type'] = isset($pro['video_type']) ? $pro['video_type'] : 'O';
            $programme['ppv_flag'] = isset($pro['ppv_flag']) ? $pro['ppv_flag'] : 0;
            $programme['subscription_flag'] = isset($pro['subscription_flag']) ? $pro['subscription_flag'] : 0;
            $programme['premium_title'] = isset($pro['premium_title']) ? $pro['premium_title'] : '';
            $programme['premium_title_zh'] = isset($pro['premium_title_zh']) ? $pro['premium_title_zh'] : '';
            $programme['premium_title_en'] = isset($pro['premium_title_en']) ? $pro['premium_title_en'] : '';
            $programme['ppv_online_time'] = isset($pro['ppv_online_time']) ? $pro['ppv_online_time'] : '';
            $programme['ppv_offline_time'] = isset($pro['ppv_offline_time']) ? $pro['ppv_offline_time'] : '';
            $programme['ppv_country_allow_list'] = isset($pro['ppv_country_allow_list']) ? $pro['ppv_country_allow_list'] : '';
            $programme['ppv_country_deny_list'] = isset($pro['ppv_country_deny_list']) ? $pro['ppv_country_deny_list'] : '';
            $programme['subscription_free_flag'] = isset($pro['subscription_free_flag']) ? $pro['subscription_free_flag'] : 0;
            $programme['subscription_online_time'] = isset($pro['subscription_online_time']) ? $pro['subscription_online_time'] : '';
            $programme['subscription_offline_time'] = isset($pro['subscription_offline_time']) ? $pro['subscription_offline_time'] : '';
            $programme['subscription_country_allow_list'] = isset($pro['subscription_country_allow_list']) ? $pro['subscription_country_allow_list'] : '';
            $programme['subscription_country_deny_list'] = isset($pro['subscription_country_deny_list']) ? $pro['subscription_country_deny_list'] : '';

            $obj = new MstatWebServiceClient();
            $ret = $obj->getVideoStats(2,AC::PERIOD);
            if( is_array($ret) && !empty($ret) )
            {
                $_data = array();
                
                foreach($ret as $_id => $data)
                {
                    if(intval($_id) == intval($id))
                    {
                        $programme['mytv_plus_view']  = $data['view'];
                        $programme['total_view'] = $data['view'];
                        $programme['mytv_plus_fav'] = $data['favour'];
                        $programme['total_fav'] = $data['favour'];
                    }
                }
            }
            //$programme_cast = self::getCastsById('programme',$id);
            $programme_array[] = $programme;
            self::getLastModifyTime($pro['modified_at']);
           
        }
        return $programme_array;
    }

    private static function getFieldById($table_name,$id)
    {
        switch($table_name)
        {
        case 'p_programme' : 
            $sql = 'SELECT * ,
            UNIX_TIMESTAMP(time_onair) as time_onair, UNIX_TIMESTAMP(first_episode_time_onair) as first_episode_time_onair,  
            UNIX_TIMESTAMP(last_episode_time_onair) as last_episode_time_onair, UNIX_TIMESTAMP(created_at) as created_at , 
            UNIX_TIMESTAMP(modified_at) as modified_at, UNIX_TIMESTAMP(production_start_date) as production_start_date,
            UNIX_TIMESTAMP(online_time) as online_time, UNIX_TIMESTAMP(offline_time) as offline_time, 
            UNIX_TIMESTAMP(ppv_online_time) as ppv_online_time, UNIX_TIMESTAMP(ppv_offline_time) as ppv_offline_time, 
            UNIX_TIMESTAMP(subscription_online_time) as subscription_online_time, 
            UNIX_TIMESTAMP(subscription_offline_time) as subscription_offline_time 
            FROM `p_programme` WHERE id = :id'; 
            ;break;
        case 'p_episode' : 
            $sql = 'SELECT *, 
            UNIX_TIMESTAMP(time_onair) as time_onair,UNIX_TIMESTAMP(modified_at) as modified_at,
            UNIX_TIMESTAMP(created_at) as created_at,UNIX_TIMESTAMP(online_time) as online_time,
            UNIX_TIMESTAMP(offline_time) as offline_time
            FROM `p_episode` WHERE id = :id'; 
            ;break;
        case 'p_video' : 
            $sql = 'SELECT * ,
            UNIX_TIMESTAMP(modified_at) as modified_at,UNIX_TIMESTAMP(created_at) as created_at,
            UNIX_TIMESTAMP(online_time) as online_time,UNIX_TIMESTAMP(offline_time) as offline_time,
            UNIX_TIMESTAMP(ppv_online_time) as ppv_online_time, UNIX_TIMESTAMP(ppv_offline_time) as ppv_offline_time, 
            UNIX_TIMESTAMP(subscription_online_time) as subscription_online_time, 
            UNIX_TIMESTAMP(subscription_offline_time) as subscription_offline_time,
            UNIX_TIMESTAMP(first_time_onair) as first_time_onair
            FROM `p_video` WHERE id = :id'; 
            ;break;
        case 'p_image'   :
        case 'p_chapter' :
        case 'p_info'    :
        case 'p_personage' : 
            $sql = 'SELECT * ,
            UNIX_TIMESTAMP(modified_at) as modified_at,UNIX_TIMESTAMP(created_at) as created_at,
            UNIX_TIMESTAMP(online_time) as online_time,UNIX_TIMESTAMP(offline_time) as offline_time
            FROM `'.$table_name.'` WHERE id = :id'; 
            ;break;
        
        default :
            $sql = 'SELECT * FROM `'.$table_name.'` WHERE id=:id';
        }

        $ret = self::selectBySql($sql,array(':id'=>$id)); 
        return isset($ret[0]) ? $ret[0] : array();
    }

    private static function getCategoryList($pid)
    {
        $result = array();
        $sql = 'SELECT  category_id_1 as category_id FROM `p_programme-category` where programme_id = :pid';
        $ret = self::selectBySql($sql,array(':pid'=>$pid));
        if(!empty($ret))
        {
            foreach($ret as $val)
            {
                $result[] = $val['category_id'];
            }
        }
        return empty($result) ? '' : implode(',',$result);
    }

    private static function getCastsById($table_name,$id)
    {
        $sql = 'SELECT casts FROM `'.$table_name.'` WHERE id=:id';
        $ret = self::selectBySql($sql,array(':id'=>$id)); 
        $casts_array = array(
            'main_cast'=>'',
            'side_cast'=>'',
            'host'=>'',
            'guest_host'=>'',
            'guest'=>'',
            'performing_guest'=>'',
            'dancer'=>'',
            'judge'=>'',
            'participant'=>'',
            'executive_producer'=>'',
            'producer'=>'',
            'supervisor'=>'',
            'editor'=>'',
            'story'=>'',
            'dubbing_artiste'=>''
        );
        if(isset($ret[0]['casts']))
        {
            $casts =  json_decode($ret[0]['casts']);
            foreach($casts as $key => $cast)
            {
                if(array_key_exists($key,$casts_array))
                {
                    $casts_array[$key] = json_encode($cast);
                }
            }
        }
        return $casts_array;
    }

    /**
     * get record status insert/update/delete
     *
     */ 
    /*
    public static function getRecordStatus($table_name,$table_id)
    {
        $_sql = 'SELECT id FROM ' .$table_name .'WHERE id = :id';
        $exists = Por::selectBySql($_sql,array(':id'=>$table_id));
        if(empty($exists))
        {
           return 'add';
        }
        else
        {
            $status_sql = 'SELECT status FROM `pdes_02`.`'.$table_name.'` WHERE id = :id';
            $status = Por::selectBySql($status_sql,array(':id'=>$table_id));
            if(AC::STATUS_DELETED == $status)
            {
                return 'del';
            }
            else
            {
                return 'edit';    
            }
                
        }

    }
     */

    public static function getPmsFolderVideo($folder_id, $video_id)
    {
        $sql = "SELECT * FROM `p_folder_item` WHERE `folder_id`=:folder_id AND `item_id`=:item_id";
        $result = self::selectBySql($sql, array(
            ':folder_id' => $folder_id,
            ':item_id' => $video_id));
        return isset($result[0]) ? $result[0] : FALSE;
    }

    public static function getPmsFolderImage($folder_id, $image_id)
    {
        $sql = "SELECT * FROM `p_folder_item` WHERE `folder_id`=:folder_id AND `item_id`=:item_id";
        $result = self::selectBySql($sql, array(
            ':folder_id' => $folder_id,
            ':item_id' => $image_id));
        return isset($result[0]) ? $result[0] : FALSE;
    }

    public static function getPmsFolder($folder_id)
    {
        return self::getFieldById('p_folder', $folder_id);
    }

    public static function getPmsImage($image_id)
    {
        return self::getFieldById('p_image', $image_id);
    }

    public static function getPmsVideo($video_id)
    {
        return self::getFieldById('p_video', $video_id);
    }

    public static function getPmsCast($cast_id)
    {
        return self::getFieldById('p_personage', $cast_id);
    }

    public static function getPmsChapter($chapter_id)
    {
        return self::getFieldById('p_chapter', $chapter_id);
    }

    public static function getPmsInfo($info_type_id, $info_id)
    {
        $sql = "SELECT * FROM `p_info` WHERE `info_type_id`=:info_type_id AND `info_id`=:info_id";
        return self::selectBySql($sql, array(
            ':info_type_id' => $info_type_id,
            'info_id' => $info_id)); 
    }

    //return string
    public function getLastModifiedTimeByProgramme($programme_id)
    {
        self::$lastModifiedTime = 0;
        self::getPortalData('p_programme', $programme_id);
        return date('Y-m-d H:i:s', self::$lastModifiedTime);
    }

    public function getLastModifiedTimeByEpisode($episode_id)
    {
        self::$lastModifiedTime = 0;
        $dataArray = self::getPortalData('p_episode', $episode_id);
        return date('Y-m-d H:i:s', self::$lastModifiedTime);
    }

    //return bool
    public function checkVideoDistributeByProgrammeId($porgramme_id)
    {
        return TRUE;
    }

    /**
     * getProgrammeVideos 
     * 
     * @param mixed $programme_id 
     * @access public
     * @return array 
     */
    public function getProgrammeVideos($programme_id)
    {
        $ret = self::getImgOrVideo('p_programme', $programme_id);
        return isset($ret['video']) ? $ret['video'] : array();
    }

    /**
     * checkVideoStatus 
     * 
     * @param mixed $source_id 
     * @access public
     * @return bool 
     */
    public function checkVideoDistributeStatus($source_id)
    {
        $octo = new OctoShapeClient;
        return $octo->getVideoStatus($source_id);
    }

    public function sendDataToPortal($dataArray)
    {
        if (AC::CONFIG_MQ && file_exists(AC::CONFIG_MQ)) {
            $config = ConfigReaderFactory::getInstance()->getConfigReader(AC::CONFIG_MQ)->getConfig();
    		$consumerConfig = $config->xpath("/config/consumer[@name='SendPremiumPortal']");
    
    		$broker = (string) $consumerConfig[0]->broker;
    		$queue  = (string) $consumerConfig[0]->queue;
    
            if ($broker && $queue) {
    		    $result = MessageHelper::sendMessage($broker, $queue, $dataArray);
                return (boolean)$result;
            }
        } 
    }
    
    public static function getFolderListPathByFolderId($folder_list)
    {
        if (empty($folder_list)) return '';

        $sql = "SELECT id, type FROM  p_folder WHERE id IN ({$folder_list})";
        $rs = self::selectBySql($sql, array());
        foreach ($rs as $row) {
            $path_list[$row['id']] = $row['type'];
        }

        $result = array();
        $folders = explode(',', $folder_list);
        foreach ($folders as $folder) {
            $result[] = $path_list[$folder];
        }

        return implode(',', $result);
    }
}
?>
